<?php

namespace App\Helpers;

use App\Models\ReportCar;
use App\Models\Vehicle;
use PhpClickHouseLaravel\RawColumn;

class ClickHouseFaker 
{
    const  ID_MAX = 71132;
    protected $id_max = 71132;

    public function __construct($max=71132)
    {
        $this->id_max = $max;
    }

    public static function generate()
    {
        $id = 1;
        $id = intval(time() / (5 * 60) % self::ID_MAX);
        file_put_contents(__DIR__ . '/record.txt', "当前ID:". $id . " ". date("Y-m-d H:i:s") . "\r\n", FILE_APPEND);   // 这个函数支持版本(PHP 5) 

        $vehicles = Vehicle::all();
        foreach($vehicles as $vehicle){
            $id = ($id + $vehicle->id) % self::ID_MAX;
            $max = ReportCar::select([new RawColumn('max(id) as id')])->getRows()[0]['id'];
            $data = ReportCar::where('id', '=', $id)->getRows();
            $position = self::getPosition($id);
            if($data){
                $data = $data[0];
                $data['id'] = $max + 1;
                $data['reqDate'] = date("Y-m-d H:i:s");
                $data['year']   = date("Y");
                $data['month']  = date("m");
                $data['day']    = date("d");
                $data['hour']   = date("H");
                $data['minute'] = date("i");
                $data['second'] = date("s");
                $data['startChar'] = "##";
                $data['longitude'] = $position[0];
                $data['latitude'] = $position[1];
                $data['Vin'] = $vehicle->VIN;
                $data['AcTime'] = date("Y-m-d H:i:s");
                $new = ReportCar::create($data);
            }

        }
        // $data
        return $new;
    }

    public static function getPosition($id=null){
        if(!$id){
            $id = intval(time() / (5 * 60) % self::ID_MAX);
        }
        $file=file(__DIR__ . '/data/Taxi_116',);

        $lines = count($file);
        $line = $id % $lines ;
        $str = (explode(",",  $file[$line]));

        return [$str[2], $str[3]];
    }


}